<template>
  <div class="order-refund-apply-list">
    <van-nav-bar title="申请退款" :border="false" fixed placeholder/>
    <van-form @submit="handleApplyRefund">
      <white-space/>
      <van-field name="kind" :value="kindLabel" label="退款方式" input-align="right" readonly/>
      <van-field v-model="reason" label="退款原因" placeholder="请选择"
                 input-align="right" readonly is-link
                 :rules="[{ required: true, message: '请选择退款原因', trigger:'onChange' }]"
                 @click="showReasonPicker = true"/>
      <van-field :value="itemStatusLabel" label="货物状态" placeholder="请选择"
                 input-align="right" readonly is-link
                 :rules="[{ required: true, message: '请选择货物状态', trigger:'onChange'}]"
                 @click="showItemStatusPicker = true"/>
      <white-space/>
      <order-refund-apply-list-item v-for="(item, index) in items" :key="item.id" :index="index" :item="item"
                                    :name="item.name" :image-url="item.imageUrl"
                                    :quantity="item.quantity"
                                    :refunding-amount="item.refundingAmount"
                                    :refunded-amount="item.refundedAmount"
                                    :total-amount="item.totalAmount"/>
      <van-cell title="退款总金额" :value="'¥ ' + totalRefundingAmount" value-class="order-refund-total-refunding-amount"/>
      <van-field v-model="notes" type="textarea" label="退款说明"
                 maxlength="200" show-word-limit placeholder="选填，最多200字"/>
      <white-space/>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit" :loading="applying">提交申请</van-button>
      </div>
      <white-space/>
      <van-popup v-model="showReasonPicker" position="bottom">
        <van-picker show-toolbar :columns="reasonColumns"
                    @confirm="handleReasonConfirm"
                    @cancel="showReasonPicker = false"/>
      </van-popup>
      <van-popup v-model="showItemStatusPicker" position="bottom">
        <van-picker show-toolbar :columns="itemStatusColumns"
                    @confirm="handleItemStatusConfirm"
                    @cancel="showItemStatusPicker = false"/>
      </van-popup>
    </van-form>
  </div>
</template>

<script>
import BigDecimal from "decimal.js"
import * as _ from "lodash"
import { message, order as Order } from "@mall/api-services"
import WhiteSpace from "@/components/WhiteSpace"
import { Button, Cell, CellGroup, Field, Form, NavBar, Picker, Popup, Toast } from "vant"
import OrderRefundApplyListItem from "@/views/order/OrderRefundApplyListItem"

const RECEIVED = "received"
const NOT_RECEIVED = "not_received"

const RECEIVED_LABEL = "已收到货"
const NOT_RECEIVED_LABEL = "未收到货"

const { OrderDisputeKind, OrderDisputeItemStatus } = Order

export default {
  name: "OrderRefundApplyList",
  components: {
    OrderRefundApplyListItem,
    WhiteSpace,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Form.name]: Form,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
  },
  props: {
    orderId: String,
    itemIds: Array,
    kind: String,
  },
  watch: {
    "$route": "refreshOrder",
    order(order) {
      const { itemIds } = this
      this.items = _.chain(order.items)
          .filter(item => _.includes(itemIds, item.id))
          .map(item => ({
            itemId: item.id,
            name: item.name,
            imageUrl: item.imageUrl,
            quantity: item.quantity,
            refundingAmount: item.refundingAmount,
            refundedAmount: item.refundedAmount,
            totalAmount: item.totalAmount,
            amount: BigDecimal.sub(item.totalAmount, BigDecimal.add(item.refundedAmount, item.refundingAmount)).toNumber(),
          }))
          .value()
    },
  },
  created() {
    this.refreshOrder()
  },
  computed: {
    kindLabel() {
      const { kind } = this
      if (kind === OrderDisputeKind.OnlyRefund) {
        return "仅退款"
      } else if (kind === OrderDisputeKind.ReturnRefund) {
        return "退货退款"
      }
      return "未知"
    },
    itemStatusLabel() {
      const { itemStatus } = this
      if (itemStatus === OrderDisputeItemStatus.Received) {
        return "已收到货"
      } else if (itemStatus === OrderDisputeItemStatus.NotReceived) {
        return "未收到货"
      }
      return undefined
    },
    totalRefundingAmount() {
      return _.chain(this.items)
          .map(item => _.isEmpty(item.amount) ? 0 : item.amount)
          .reduce((sum, n) => BigDecimal.add(sum, n).toNumber(), 0)
          .value()
    },
  },
  data() {
    return {
      reasonColumns: ["未按约定时间发货", "拍错/多拍/不喜欢", "协商一致退款", "其他"],
      showReasonPicker: false,
      itemStatusColumns: [RECEIVED_LABEL, NOT_RECEIVED_LABEL],
      showItemStatusPicker: false,
      order: new Order.Order(),
      reason: "",
      itemStatus: "",
      notes: "",
      items: [],
      applying: false,
    }
  },
  methods: {
    refreshOrder() {
      if (this.showKind) {
        return
      }
      Toast.loading()
      Order.OrderServiceV1
          .getOrder(this.orderId)
          .then(order => this.order = order)
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => Toast.clear())
    },
    handleItemStatusConfirm(status) {
      if (status === RECEIVED_LABEL) {
        this.itemStatus = RECEIVED
      } else if (status === NOT_RECEIVED_LABEL) {
        this.itemStatus = NOT_RECEIVED
      }
      this.showItemStatusPicker = false
    },
    handleReasonConfirm(reason) {
      this.reason = reason
      this.showReasonPicker = false
    },

    handleApplyRefund() {
      const { orderId, kind, itemStatus, reason, notes, items } = this
      const refunds = _.chain(items)
          .map(item => _.assign(new Order.OrderRefund(), {
            kind, itemStatus, reason, notes,
            itemId: item.itemId,
            amount: item.amount,
          }))
          .value()
      this.applying = true
      Order.OrderServiceV1.applyOrderRefunds(orderId, refunds)
          .then(() => new Promise(resolve => {
            Toast.success({
              message: "申请成功",
              duration: 2000,
              onClose: resolve,
            })
          }))
          .then(() => this.$router.go(-3))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.applying = false)
    },
  },
}
</script>

<style lang="scss" scoped>
@import "../../styles/variables";

.order-refund-apply-list {
  .order-refund-total-refunding-amount {
    color: $orange-dark;
  }
}
</style>
